package main

import (
	"database/sql"

	"test.com/worlddb"
)

type questionDialogTableRow struct {
	QuestionID uint32   `json:"questionID"`
	Question   string   `json:"question"`
	Options    []string `json:"options"`
}

func getAllQuestion4DialogTable(db *sql.DB) ([]*questionDialogTableRow, error) {
	var questionRows []*questionDialogTableRow
	questionMaps := map[uint32]*questionDialogTableRow{}
	rows, err := db.Query("SELECT Id FROM quest_question ORDER BY Id")
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var Id uint32
		if err = rows.Scan(&Id); err == nil {
			questionRows = append(questionRows, &questionDialogTableRow{QuestionID: Id})
			questionMaps[Id] = questionRows[len(questionRows)-1]
		} else {
			return nil, err
		}
	}
	rows, err = db.Query("SELECT stringID,stringCN FROM string_text_list WHERE "+
		"stringID>=?<<24 AND stringID<?<<24 AND stringID&0xff IN (1,2,4,6,8) "+
		"ORDER BY stringID",
		worlddb.STRING_TEXT_TYPE_QUESTION, worlddb.STRING_TEXT_TYPE_QUESTION+1)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var stringID uint32
		var stringCN string
		if err = rows.Scan(&stringID, &stringCN); err == nil {
			questionRow := questionMaps[(stringID>>8)&0xffff]
			switch stringID & 0xff {
			case 1:
				questionRow.Question = stringCN
			case 2, 4, 6, 8:
				questionRow.Options = append(questionRow.Options, stringCN)
			}
		} else {
			return nil, err
		}
	}
	return questionRows, nil
}
